// 商品列表页面逻辑
Page({
  data: {
    userInfo: {},
    searchKeyword: '',
    currentTab: 'all',
    allGoods: [],
    filteredGoods: [],
    hasMore: true,
    page: 1,
    pageSize: 20
  },

  onLoad() {
    this.loadUserInfo();
    this.loadGoodsList();
  },

  // 加载用户信息
  loadUserInfo() {
    const app = getApp();
    // 优先从userInfo1中获取用户信息，如果没有则从userInfo中获取
    let userInfo = app.getUserInfo1() || app.globalData.userInfo || {};
    
    // 如果从userInfo1获取到数据，将totalPoint映射为points
    if (userInfo.totalPoint !== undefined) {
      userInfo = {
        ...userInfo,
        points: userInfo.totalPoint || 0 // 将totalPoint映射为points字段
      };
    }
    
    this.setData({
      userInfo: userInfo
    });
    
    console.log('商品列表页面加载的用户信息:', userInfo);
  },

  // 加载商品列表
  loadGoodsList() {
    let token = '';
    try {
      token = wx.getStorageSync('token');
    } catch (e) {
      console.error('获取token失败', e);
    }

    wx.showLoading({
      title: '加载中...',
      mask: true
    });

    // 调用后端接口获取商品列表（多表联查，支持分页和筛选）
    wx.request({
      url: 'http://localhost:8080/point/goods/list-with-stats',
      method: 'GET',
      header: {
        'Authorization': token,
        'Content-Type': 'application/json'
      },
      data: {
        pageNum: this.data.page,
        pageSize: this.data.pageSize
      },
      success: (res) => {
        console.log(res);
        wx.hideLoading();
        if (res.data.code === 200) {
          const goodsList = res.data.rows || [];
          const total = res.data.total || 0;
          
          // 转换数据格式，根据实际API返回的字段名
          const allGoods = goodsList.map(item => ({
            id: item.id,
            title: item.name || item.title,
            desc: item.desc || item.description,
            imageUrl: item.coverImg || item.coverUrl || item.imageUrl,
            points: item.point || item.points || item.pointPrice,
            originalPrice: item.originalPrice || item.marketPrice,
            tags: this.generateTags(item),
            type: this.getGoodsType(item),
            stock: item.stock || 0,
            sales: item.sales || 0,
            validityDays: item.validityDays || 0,
            exchangeCount: item.exchangeCount || 0,
            status: item.status
          }));

          this.setData({
            allGoods: allGoods,
            filteredGoods: allGoods,
            hasMore: this.data.page * this.data.pageSize < total
          });

          this.filterGoods();
        } else {
          wx.showToast({
            title: res.data.msg || '获取商品列表失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        wx.hideLoading();
        console.error('获取商品列表失败', err);
        wx.showToast({
          title: '获取商品列表失败',
          icon: 'none'
        });
      }
    });
  },

  // 加载热门商品列表（按销量排序）
  loadHotGoodsList() {
    let token = '';
    try {
      token = wx.getStorageSync('token');
    } catch (e) {
      console.error('获取token失败', e);
    }

    wx.showLoading({
      title: '加载中...',
      mask: true
    });

    // 调用热门商品接口（按销量排序）
    wx.request({
      url: 'http://localhost:8080/point/goods/hot/sales',
      method: 'GET',
      header: {
        'Authorization': token,
        'Content-Type': 'application/json'
      },
      data: {
        limit: 50 // 获取50个热门商品
      },
      success: (res) => {
        console.log('热门商品API返回数据:', res.data);
        wx.hideLoading();
        
        if (res.data.code === 200) {
          const goodsList = res.data.data || [];
          
          // 转换数据格式
          const allGoods = goodsList.map(item => ({
            id: item.id,
            title: item.name || item.title,
            desc: item.desc || item.description,
            imageUrl: item.coverImg || item.coverUrl || item.imageUrl,
            points: item.point || item.points || item.pointPrice,
            originalPrice: item.originalPrice || item.marketPrice,
            tags: this.generateTags(item),
            type: 'hot', // 标记为热门商品
            stock: item.stock || 0,
            sales: item.sales || 0,
            validityDays: item.validityDays || 0,
            exchangeCount: item.exchangeCount || 0,
            status: item.status
          }));

          this.setData({
            allGoods: allGoods,
            filteredGoods: allGoods,
            hasMore: false // 热门商品不分页
          });

          console.log('热门商品加载完成，数量:', allGoods.length);
        } else {
          wx.showToast({
            title: res.data.msg || '获取热门商品失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        wx.hideLoading();
        console.error('获取热门商品失败', err);
        wx.showToast({
          title: '获取热门商品失败',
          icon: 'none'
        });
      }
    });
  },

  // 加载新品列表（按时间排序）
  loadNewGoodsList() {
    let token = '';
    try {
      token = wx.getStorageSync('token');
    } catch (e) {
      console.error('获取token失败', e);
    }

    wx.showLoading({
      title: '加载中...',
      mask: true
    });

    // 调用新品接口（按创建时间排序）
    wx.request({
      url: 'http://localhost:8080/point/goods/new',
      method: 'GET',
      header: {
        'Authorization': token,
        'Content-Type': 'application/json'
      },
      data: {
        limit: 50 // 获取50个新品
      },
      success: (res) => {
        console.log('新品API返回数据:', res.data);
        wx.hideLoading();
        
        if (res.data.code === 200) {
          const goodsList = res.data.data || [];
          
          // 转换数据格式
          const allGoods = goodsList.map(item => ({
            id: item.id,
            title: item.name || item.title,
            desc: item.desc || item.description,
            imageUrl: item.coverImg || item.coverUrl || item.imageUrl,
            points: item.point || item.points || item.pointPrice,
            originalPrice: item.originalPrice || item.marketPrice,
            tags: this.generateTags(item),
            type: 'new', // 标记为新品
            stock: item.stock || 0,
            sales: item.sales || 0,
            validityDays: item.validityDays || 0,
            exchangeCount: item.exchangeCount || 0,
            status: item.status
          }));

          this.setData({
            allGoods: allGoods,
            filteredGoods: allGoods,
            hasMore: false // 新品不分页
          });

          console.log('新品加载完成，数量:', allGoods.length);
        } else {
          wx.showToast({
            title: res.data.msg || '获取新品失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        wx.hideLoading();
        console.error('获取新品失败', err);
        wx.showToast({
          title: '获取新品失败',
          icon: 'none'
        });
      }
    });
  },

  // 生成商品标签
  generateTags(item) {
    const tags = [];
    
    // 根据商品属性生成标签
    if (item.exchangeCount > 0) {
      tags.push('热门');
    }
    if (item.stock > 0 && item.stock < 50) {
      tags.push('限时');
    }
    if (item.validityDays > 0) {
      tags.push('有效期');
    }
    if (item.sales > 100) {
      tags.push('热销');
    }
    
    return tags;
  },

  // 获取商品类型
  getGoodsType(item) {
    const tags = this.generateTags(item);
    if (tags.includes('热门') || tags.includes('热销')) {
      return 'hot';
    } else if (tags.includes('限时')) {
      return 'discount';
    } else if (item.stock > 0 && item.stock < 30) {
      return 'new';
    }
    return 'all';
  },

  // 搜索输入
  onSearchInput(e) {
    this.setData({
      searchKeyword: e.detail.value
    });
  },

  // 搜索
  onSearch() {
    console.log('执行搜索，关键词:', this.data.searchKeyword);
    this.filterGoods();
  },

  // 切换标签
  switchTab(e) {
    const tab = e.currentTarget.dataset.tab;
    this.setData({
      currentTab: tab,
      page: 1, // 重置页码
      allGoods: [], // 清空商品列表
      filteredGoods: [], // 清空筛选结果
      hasMore: true // 重置加载更多状态
    });
    
    // 根据标签加载不同的数据
    if (tab === 'all') {
      this.loadGoodsList();
    } else if (tab === 'hot') {
      this.loadHotGoodsList();
    } else if (tab === 'new') {
      this.loadNewGoodsList();
    }
  },

  // 筛选商品
  filterGoods() {
    const { currentTab, allGoods, searchKeyword } = this.data;
    let filtered = [];

    // 按标签筛选
    if (currentTab === 'all') {
      filtered = allGoods;
    } else if (currentTab === 'hot') {
      // 热门商品已经通过接口筛选，这里只需要处理搜索
      filtered = allGoods;
    } else if (currentTab === 'new') {
      // 新品已经通过接口筛选，这里只需要处理搜索
      filtered = allGoods;
    }

    // 按关键词搜索
    if (searchKeyword.trim()) {
      filtered = filtered.filter(item => 
        item.title.includes(searchKeyword) || 
        item.desc.includes(searchKeyword)
      );
    }

    this.setData({
      filteredGoods: filtered
    });

    console.log(`筛选完成 - 标签: ${currentTab}, 关键词: "${searchKeyword}", 结果数量: ${filtered.length}`);
  },

  // 商品详情
  onGoodsDetail(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/my/pages/goods-detail/goods-detail?id=${id}`
    });
  },

  // 兑换商品
  onExchangeItem(e) {
    const item = e.currentTarget.dataset.item;
    
    if (this.data.userInfo.points < item.points) {
      wx.showToast({
        title: '积分不足',
        icon: 'none'
      });
      return;
    }

    // 跳转到商品详情页面
    wx.navigateTo({
      url: `/my/pages/goods-detail/goods-detail?id=${item.id}`
    });
  },

  // 加载更多
  loadMore() {
    const { currentTab, hasMore } = this.data;
    
    if (!hasMore) {
      wx.showToast({
        title: '没有更多数据了',
        icon: 'none'
      });
      return;
    }

    // 只有"全部"标签支持分页加载更多
    if (currentTab !== 'all') {
      wx.showToast({
        title: '当前标签不支持加载更多',
        icon: 'none'
      });
      return;
    }

    this.setData({
      page: this.data.page + 1
    });

    let token = '';
    try {
      token = wx.getStorageSync('token');
    } catch (e) {
      console.error('获取token失败', e);
    }

    wx.showLoading({
      title: '加载中...',
      mask: true
    });

    // 调用后端接口加载更多数据
    wx.request({
      url: 'http://localhost:8080/point/goods/list-with-stats',
      method: 'GET',
      header: {
        'Authorization': token,
        'Content-Type': 'application/json'
      },
      data: {
        pageNum: this.data.page,
        pageSize: this.data.pageSize
      },
      success: (res) => {
        wx.hideLoading();
        if (res.data.code === 200) {
          const newGoodsList = res.data.rows || [];
          const total = res.data.total || 0;
          
          const formattedNewGoods = newGoodsList.map(item => ({
            id: item.id,
            title: item.name || item.title,
            desc: item.desc || item.description,
            imageUrl: item.coverImg || item.coverUrl || item.imageUrl,
            points: item.point || item.points || item.pointPrice,
            originalPrice: item.originalPrice || item.marketPrice,
            tags: this.generateTags(item),
            type: this.getGoodsType(item),
            stock: item.stock || 0,
            sales: item.sales || 0,
            validityDays: item.validityDays || 0,
            exchangeCount: item.exchangeCount || 0,
            status: item.status
          }));

          const allGoods = [...this.data.allGoods, ...formattedNewGoods];
          this.setData({
            allGoods: allGoods,
            page: this.data.page,
            hasMore: this.data.page * this.data.pageSize < total
          });
          this.filterGoods();
        }
      },
      fail: (err) => {
        wx.hideLoading();
        console.error('加载更多失败', err);
        wx.showToast({
          title: '加载更多失败',
          icon: 'none'
        });
      }
    });
  },

  // 分享
  onShareAppMessage() {
    return {
      title: '积分商城',
      path: '/my/pages/goods-list/goods-list'
    };
  }
}); 